﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Microsoft.Win32;

//    Copyright (C) 2011 Officebroker.com LTD.
//    Neil Cadman, Alex Welding, Andrew Coombs, Jan Rygielski
//    Sir Robert Peel Mill, Mill Lane, Staffordshire, Fazely, B78 3QD, England
//
//    This file is part of AMIProxy Project.
//
//    AMIProxy Project is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    AMIProxy Project is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License (GNU AGPL)
//    along with AMIProxy Project.  If not, see <http://www.gnu.org/licenses/>.

namespace AMIProxy.AMIProxyService
{
    public partial class AMIProxy : ServiceBase
    {

        // Private Variables
        private const String EVENTLOGNAME = "Asterisk AMIProxy Service Log";
        private const String EVENTLOGSOURCE = "Asterisk AMIProxy Service";
        private const string RegKey = @"SOFTWARE\AMIProxy";
        private AMIProxyLogic.AMIProxy _amiProxy;

        // Public Constructors
        public AMIProxy()
        {
            InitializeComponent();

            if (!EventLog.SourceExists(EVENTLOGSOURCE))
            {
                EventLog.CreateEventSource(EVENTLOGSOURCE, EVENTLOGNAME);
            }
        }

        // Internal Methods
        internal void startup(String[] args)
        {
            Boolean error = false;
            RegistryKey mainKey = Registry.LocalMachine;
            String errorM = "";
            String username = "";
            String password = "";
            String hostname = "";
            String sendFromAddress = "";
            String sendToAddress = "";
            String smtpServer = "";
            String logPath = "";
            Boolean logging = false;
            Int32 port = 0;

            mainKey = mainKey.OpenSubKey(RegKey, true);
            if (mainKey != null)
            {
                username = (String)mainKey.GetValue("username", "");
                password = (String)mainKey.GetValue("password", "");
                hostname = (String)mainKey.GetValue("hostname", "");
                sendFromAddress = (String)mainKey.GetValue("sendFromAddress", "");
                sendToAddress = (String)mainKey.GetValue("sendToAddress", "");
                smtpServer = (String)mainKey.GetValue("smtpServer", "");
                logPath = (String)mainKey.GetValue("logPath", "");
                logging = Convert.ToBoolean(mainKey.GetValue("logging", "false"));
                Int32.TryParse((String)mainKey.GetValue("port", ""), out port);

                if (username == "")
                {
                    errorM += "Missing username\n";
                    error = true;
                }

                if (hostname == "")
                {
                    errorM += "Missing hostname\n";
                    error = true;
                }

                if (sendFromAddress == "")
                {
                    errorM += "Missing sendFromAddress\n";
                    error = true;
                }

                if (sendToAddress == "")
                {
                    errorM += "Missing sendToAddress\n";
                    error = true;
                }

                if (smtpServer == "")
                {
                    errorM += "Missing smtpServer\n";
                    error = true;
                }

                if (logPath == "")
                {
                    errorM += "Missing logPath\n";
                    error = true;
                }

                if (port == 0)
                {
                    errorM += "Missing port\n";
                    error = true;
                }
            }
            else
            {
                errorM += "Missing \"" + RegKey + "\" Key\n";
                error = true;
            }

            if (error)
            {
                EventLog errorLog = new EventLog();
                errorLog.Source = EVENTLOGSOURCE;
                errorLog.WriteEntry("Could not start service, the following reason(s) apply\n\n" + errorM, EventLogEntryType.Error, 1000);

                this.Stop();
                return;
            }

            _amiProxy = new AMIProxyLogic.AMIProxy();
            _amiProxy.InitiateConnection(username, password, hostname, port, sendFromAddress, sendToAddress, smtpServer, logPath, logging);
           
            // DEBUGGER
            //_amiProxy.DebugTextFile("peers.txt", "test.txt");
        }

        // Private Methods
        private void LogEvent(String errorMessage, EventLogEntryType eventType)
        {
            LogEvent(errorMessage, eventType, -1);
        }
        private void LogEvent(String errorMessage, EventLogEntryType eventType, Int32 eventID)
        {
            EventLog errorLog = new EventLog();
            errorLog.Source = EVENTLOGSOURCE;

            if (eventID == -1)
                errorLog.WriteEntry(errorMessage, eventType);
            else
                errorLog.WriteEntry(errorMessage, eventType, eventID);
        }

        // Protected Methods
        protected override void OnStart(String[] args)
        {
            LogEvent("Service Started", EventLogEntryType.Information);
            startup(args);
        }
        protected override void OnStop()
        {
            if (_amiProxy != null)
            {
                _amiProxy.SendErrorReport("AMI Proxy Service has shut down", null);
                _amiProxy.ShutdownServer();
            }
        }
    
    }
}
